package com.app.oral.service.impl

import com.app.oral.dao.ClassMapper
import com.app.oral.dao.UserMapper
import com.app.oral.model.ClassInfo
import com.app.oral.service.ClassService
import com.qcloud.cos.COSClient
import org.springframework.stereotype.Service
import java.math.BigInteger

@Service
class ClassServiceImpl(
    private val classMapper: ClassMapper,
    private val userMapper: UserMapper
) : ClassService {
    
    override fun getAllClasses(): List<ClassInfo> {
        return classMapper.findAllClasses()
    }
    
    override fun getClassesByGrade(grade: Int): List<ClassInfo> {
        return classMapper.findClassesByGrade(grade)
    }
    
    override fun getClassById(id: Long): ClassInfo? {
        return classMapper.findById(id)
    }
    
    override fun getClassStudentCount(classId: Long): Int {
        return userMapper.countStudentsByClassId(classId)
    }
    
    override fun createClass(grade: Int, className: String): ClassInfo {
        val params = mutableMapOf<String, Any>(
            "grade" to grade,
            "className" to className
        )
        
        val rowsAffected = classMapper.insertClass(params)
        if (rowsAffected > 0) {
            val insertedId = when (val id = params["insertedId"]) {
                is Long -> id
                is BigInteger -> id.toLong()
                is Number -> id.toLong()
                else -> throw RuntimeException("无法获取插入的班级ID")
            }
            return classMapper.findById(insertedId) 
                ?: throw RuntimeException("创建班级后无法查询到插入的记录")
        } else {
            throw RuntimeException("班级创建失败")
        }
    }
    
    override fun deleteClass(id: Long): Boolean {
        return classMapper.deleteById(id) > 0
    }
    
    override fun existsByGradeAndClassName(grade: Int, className: String): Boolean {
        return classMapper.existsByGradeAndClassName(grade, className)
    }
}